package com.example.lianjuan.ui.frament;

import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.example.lianjuan.Base.BaseFragment;
import com.example.lianjuan.Base.IBaseInfo;
import com.example.lianjuan.Base.IlinearInfo;
import com.example.lianjuan.Model.domain.Categories;
import com.example.lianjuan.Model.domain.HomePagerCategories;
import com.example.lianjuan.Presenter.impl.ICategoryPagerPresenter;
import com.example.lianjuan.R;
import com.example.lianjuan.Utils.Constants;
import com.example.lianjuan.Utils.LogUtils;
import com.example.lianjuan.Utils.PresenterManang;
import com.example.lianjuan.Utils.SizeUtils;
import com.example.lianjuan.Utils.TicketUtil;
import com.example.lianjuan.Utils.ToastUtil;
import com.example.lianjuan.View.ICategoryPagerCallback;
import com.example.lianjuan.ui.adapter.LinearItemContentAdapter;
import com.example.lianjuan.ui.adapter.looperPagerAdapter;
import com.example.lianjuan.ui.custom.HomePagerNestedScrollView;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider;

import java.util.List;

public class HomePagerFrament extends BaseFragment implements ICategoryPagerCallback, LinearItemContentAdapter.OnItemClickListener, looperPagerAdapter.OnLooperItemClickLister {

    private ICategoryPagerPresenter mCategoryPagerPresenter;
    private int mMaterialId;
    private RecyclerView mContentList;
    private LinearItemContentAdapter mContentAdapter;
    private ViewPager2 looperPager;
    private looperPagerAdapter mLooperPagerAdapter;
    private TextView homeTitleTv;
    private LinearLayout looperPointContainer;
    private SmartRefreshLayout mRefreshLayout;
    private LinearLayout homePagerFragment;
    private LinearLayout homeHead;
    private HomePagerNestedScrollView mNestedScrollView;
    private Handler mHandler = new Handler(Looper.myLooper());


    public static HomePagerFrament newInstance(Categories.DataDTO dataDTO) {
        HomePagerFrament homePagerFrament = new HomePagerFrament();
        Bundle bundle = new Bundle();
        bundle.putString(Constants.KEY_HOME_PAGER_TITLE, dataDTO.getTitle());
        bundle.putInt(Constants.KEY_HOME_PAGER_MATERIAL_ID, dataDTO.getId());
        homePagerFrament.setArguments(bundle);
        return homePagerFrament;
    }

    @Override
    protected void initPresenter() {
        mCategoryPagerPresenter = PresenterManang.getInstance().getCategoryPagerPresenter();
        mCategoryPagerPresenter.registerViewCallback(this);
    }

    @Override
    protected int getRootViewResID() {
        return R.layout.home_pager_frament;
    }

    @Override
    protected void initView(View view) {
        homeTitleTv = view.findViewById(R.id.home_pager_title);
        mContentList = view.findViewById(R.id.home_pager_content_list);
        looperPager = view.findViewById(R.id.looper_pager);
        looperPointContainer = view.findViewById(R.id.looper_point_container);
        mRefreshLayout = view.findViewById(R.id.home_pager_refresh);
        homePagerFragment = view.findViewById(R.id.home_pager_fragment);
        homeHead = view.findViewById(R.id.home_head_view);
        mNestedScrollView = view.findViewById(R.id.nested_scroll_view);
        //设置SmartRefreshLayout属性
        //开启嵌套滚动NestedScrolling（默认false-智能开启）
        mRefreshLayout.setEnableNestedScroll(false);
        //禁止下拉刷新
        mRefreshLayout.setEnableRefresh(false);
        //设置布局管理器
        mContentList.setLayoutManager(new LinearLayoutManager(getContext()));
        //设置间距
        mContentList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int i = SizeUtils.dip2px(getContext(), 5);
                outRect.top = i;
                outRect.bottom = i;
            }
        });
        //创建适配器
        mLooperPagerAdapter = new looperPagerAdapter();
        mContentAdapter = new LinearItemContentAdapter();
        mContentList.setAdapter(mContentAdapter);
        looperPager.setAdapter(mLooperPagerAdapter);
        //刷新头部显示
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
    }

    @Override
    protected void loadData() {
        Bundle bundle = getArguments();
        String title = bundle.getString(Constants.KEY_HOME_PAGER_TITLE);
        mMaterialId = bundle.getInt(Constants.KEY_HOME_PAGER_MATERIAL_ID);
        LogUtils.d(this, "string------>" + title + "int----->" + mMaterialId);
        //给推荐title加载数据
        homeTitleTv.setText(title);
        mCategoryPagerPresenter.getContentByCategoriesId(mMaterialId);
    }

    @Override
    public void onCategoriseLoaded(List<HomePagerCategories.DataDTO> data) {
        //正常的加载页面
        mContentAdapter.setData(data);
        setUpState(State.SUCCESS);
    }

    @Override
    protected void initListener() {
        //BUG：按住recycleView下滑，导致刷新控件认为到底部，而刷新。解决：加长recycleView的高度，这样会导致预加载时卡顿。(先不解决)
        //TODO：先不解决此BUG，难以触发
//        mNestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
//            @Override
//            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//                LogUtils.d(HomePagerFrament.this, "HomePagerFrament--->" + scrollY);
//                if (scrollY > mNestedScrollView.getHeadHeight()+mNestedScrollView.getHeadHeight()) {
//                    //允许RecycleView滑动
//                    LogUtils.d(HomePagerFrament.this, "HomePagerFrament--->" + scrollY);
//                    //mContentList.setNestedScrollingEnabled(true);
//                } else {
//                    //禁止RecycleView滑动
//                    //mContentList.setNestedScrollingEnabled(false);
//                }
//            }
//        });
        //禁止RecycleView滑动
        //mContentList.setNestedScrollingEnabled(false);
        //点击的数据回调
        mContentAdapter.setOnItemClickListener(this);
        //轮播图点击的数据回调
        mLooperPagerAdapter.setLooperItemClickLister(this);
        //解决NestedScrollView和RecyclerView加载大量的数据时卡顿
        homePagerFragment.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //拦截滑动的高度
                int headHeight = homeHead.getMeasuredHeight();
                LogUtils.d(HomePagerFrament.this, "headHeight---->" + headHeight);
                mNestedScrollView.setHeadHigh(headHeight);
                //获得最外层布局的高度(相当于手机的屏幕高度)
                int measuredHeight = homePagerFragment.getMeasuredHeight();
                //把获得的高度设置给RecyclerView,这样只会加载少量的数据
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mContentList.getLayoutParams();
                layoutParams.height = (measuredHeight);
                mContentList.setLayoutParams(layoutParams);
                //当高度不等于0的时候,才监听
                if (measuredHeight != 0) {
                    homePagerFragment.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }
        });
        //注册轮播图的滚动事件监听器
        looperPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (mLooperPagerAdapter.getSize() != 0) {
                    int targetPosition = position % mLooperPagerAdapter.getSize();
                    //切换指示器
                    upDataLooperIndicator(targetPosition);
                }
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //加载更多，下拉刷新设置为false
                if (mCategoryPagerPresenter != null) {
                    mCategoryPagerPresenter.onLoadMore(mMaterialId);
                    LogUtils.d(HomePagerFrament.this, "触发了加载更多......");
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

            }
        });
//        网络错误点击重新加载
        networkClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCategoryPagerPresenter != null) {
                    mCategoryPagerPresenter.reload(mMaterialId);
                }
            }
        });
    }

    private void upDataLooperIndicator(int targetPosition) {
        for (int i = 0; i < looperPointContainer.getChildCount(); i++) {
            View positionChildAt = looperPointContainer.getChildAt(i);
            if (i == targetPosition) {
                positionChildAt.setBackgroundResource(R.drawable.shape_indicator_select);
            } else {
                positionChildAt.setBackgroundResource(R.drawable.shape_indicator);
            }
        }

    }

    @Override
    public int getCategoryId() {
        //返回商品的ID给Presenter层
        return mMaterialId;
    }

    @Override
    public void onNetworkError() {
        //加载网页错误页面
        setUpState(State.ERROR);
    }

    @Override
    public void onLoadEmpty() {

    }

    @Override
    public void onLoadNone() {

    }

    @Override
    public void onLoaderMoreNetworkError() {
        //ToastUtil.showToast("网络错误，请重试");
        if (mRefreshLayout != null) {
            mRefreshLayout.finishLoadMore();
        }
    }

    @Override
    public void onLoaderMoreEmpty() {

    }

    @Override
    public void onLoaderMoreLoaded(List<HomePagerCategories.DataDTO> data) {
        if (mContentAdapter != null) {
            mContentAdapter.addMoreData(data);
            ToastUtil.showToast("添加了" + data.size() + "条");
            if (mRefreshLayout != null) {
                mRefreshLayout.finishLoadMore();
            }
        }

    }

    @Override
    public void onLooperListMoreLoaded(List<HomePagerCategories.DataDTO> data) {
        LogUtils.d(this, "轮播图数据长度---->" + data.size());
        mLooperPagerAdapter.setData(data);
        //设置中间点,并且设置为0
        int dx = (Integer.MAX_VALUE / 2) % data.size();
        int targetCenterPosition = (Integer.MAX_VALUE / 2) - dx;
        looperPager.setCurrentItem(targetCenterPosition);
        //先清空视图
        looperPointContainer.removeAllViews();
        //轮播图指示器
        for (int i = 0; i < data.size(); i++) {
            ImageView imageView = new ImageView(getContext());
            if (i == 0) {
                imageView.setBackgroundResource(R.drawable.shape_indicator_select);
            } else {
                imageView.setBackgroundResource(R.drawable.shape_indicator);
            }
            //为指示点添加间距
            int size = SizeUtils.dip2px(getContext(), 8);
            LinearLayout.LayoutParams layoutParams =
                    new LinearLayout.LayoutParams(size, size);
            //设置指示器边距
            layoutParams.setMarginEnd(SizeUtils.dip2px(getContext(), 3));
            // layoutParams.rightMargin = SizeUtils.dip2px(getContext(), 2);
            // layoutParams.leftMargin = SizeUtils.dip2px(getContext(), 2);
            imageView.setLayoutParams(layoutParams);
            //将指示点添加进容器
            looperPointContainer.addView(imageView);
        }
    }

    @Override
    public void onRelease(List<HomePagerCategories.DataDTO> data) {
        if (mContentAdapter != null) {
            mContentAdapter.addReleaseData(data);
            //ToastUtil.showToast("刷新" + data.size() + "条");
            if (mRefreshLayout != null) {
                mRefreshLayout.finishLoadMore();
            }
        }
    }


    @Override
    public void onLoadLoading() {
        //加载中页面
        setUpState(State.LOADING);
    }

    @Override
    public void onLoadError() {

    }

    @Override
    protected void release() {
        if (mCategoryPagerPresenter != null) {
            mCategoryPagerPresenter.unregisterViewCallback(this);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mHandler.postDelayed(mRunnable, 4000);
    }

    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeCallbacks(mRunnable);
    }

    /**
     * 轮播图
     */
    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            int currentPosition = looperPager.getCurrentItem();
            currentPosition++;
            looperPager.setCurrentItem(currentPosition, true);
            mHandler.postDelayed(mRunnable, 4000);
        }
    };

    @Override
    public void onItemClick(IlinearInfo iBaseInfo) {
        handlerActivity(iBaseInfo);
    }

    private void handlerActivity(IBaseInfo iBaseInfo) {
        TicketUtil.toTickerPager(getContext(), iBaseInfo);
    }

    @Override
    public void onLooperItemClick(IBaseInfo iBaseInfo) {
        handlerActivity(iBaseInfo);
    }
}
